import { getInroOutroFiles } from "@/services/api/api-parameter-settings";
import { DrawerForm, ProList } from "@ant-design/pro-components";
import { Image, Button, Tag, message } from "antd";

interface MediaItem {
  id: string;
  name: string;
  url: string;
  coverUrl?: string;
  duration?: number;
}

interface MediaSelectDrawerProps {
  visible: boolean;
  onClose: () => void;
  onSelect: (item: MediaItem) => void;
  mediaType: "video" | "audio";
}

const MediaSelectDrawer: React.FC<MediaSelectDrawerProps> = ({
  visible,
  onClose,
  onSelect,
  mediaType,
}) => {
  // 格式化时长显示
  const formatDuration = (duration?: number) => {
    if (!duration) return "未知时长";
    const minutes = Math.floor(duration / 60);
    const seconds = duration % 60;
    return `${minutes}分${seconds}秒`;
  };

  return (
    <DrawerForm
      title={`选择${mediaType === "video" ? "视频" : "音乐"}`}
      width={800}
      open={visible}
      submitter={false}
      onOpenChange={(open) => {
        if (!open) onClose();
      }}
    >
      <ProList<MediaItem>
        rowKey="id"
        request={async (params = {}) => {
          // 只有当抽屉打开时才请求数据
          if (!visible) {
            return { data: [], success: true, total: 0 };
          }

          const { current = 1, pageSize = 10 } = params;

          try {
            const res = await getInroOutroFiles({
              type: mediaType,
              page: current,
              pageSize
            });

            // 根据API响应结构调整
            const data = res.data?.list || res.data || [];
            const total = res.data?.total || data.length || 0;

            return {
              data,
              success: true,
              total,
            };
          } catch (error) {
            console.error("获取媒体列表失败:", error);
            message.error("获取媒体列表失败");
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
        metas={{
          title: {
            dataIndex: 'name',
          },
          description: {
            render: (_, record) => (
              <div>
                {record.url && (
                  <Tag color="blue">
                    {mediaType === "video" ? "视频" : "音频"}文件
                  </Tag>
                )}
              </div>
            ),
          },

          actions: {
            render: (_, record) => [
              <Button
                key="select"
                type="link"
                onClick={() => onSelect(record)}
              >
                选择
              </Button>,
            ],
          },
        }}
      />
    </DrawerForm>
  );
};

export default MediaSelectDrawer;
